﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using Arizu.Repository;
using System.Drawing;
using System.Drawing.Imaging;

namespace AiRiZu
{
    /// <summary>
    /// File Upload httphandler to receive files and save them to the server.
    /// </summary>
    public class FileUpload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            const string path = "Capture/Images";
            bool isCut = false;
            String filename = HttpContext.Current.Request.Headers["X-File-Name"];

            if (string.IsNullOrEmpty(filename) && HttpContext.Current.Request.Files.Count <= 0)
            {
                context.Response.Write("{success:false}");
            }
            else
            {
                string mapPath = HttpContext.Current.Server.MapPath(path);

                mapPath = mapPath.Substring(0, mapPath.LastIndexOf("handler")) + path;

                if (Directory.Exists(mapPath) == false)
                {
                    Directory.CreateDirectory(mapPath);
                }
                if (filename == null)
                {
                    //This work for IE
                    try
                    {
                        HttpPostedFile uploadedfile = context.Request.Files[0];
                        filename = uploadedfile.FileName;
                        filename = filename.Substring(filename.LastIndexOf("\\") + 1, filename.Length - (filename.LastIndexOf("\\") + 1));
                        uploadedfile.SaveAs(mapPath + "\\" + filename);

                        System.Drawing.Image bmp = System.Drawing.Image.FromStream(uploadedfile.InputStream);
                        if (bmp.Width > 200 || bmp.Height > 200)
                        {
                            if (bmp.Width > bmp.Height)
                            {
                                CompressJpegHeight(mapPath + "\\" + filename, 200, 500L);
                            }
                            else
                            {
                                CompressJpegWidth(mapPath + "\\" + filename, 200, 500L);
                            }
                            isCut = true;
                        }

                        context.Response.Write("{success:true, name:\"" + filename + "\", path:\"" + path + "/" + filename + "\", isCut:\"" + isCut + "\"}");

                    }
                    catch (Exception e)
                    {
                        context.Response.Write("{success:false}");

                    }
                }
                // not usalbe
                //else
                //{
                //    //This work for Firefox and Chrome.
                //    c

                //    try
                //    {
                //        Stream inputStream = HttpContext.Current.Request.InputStream;
                //        //inputStream.CopyTo();
                //        context.Response.Write("{success:true, name:\"" + filename + "\", path:\"" + path + "/" + filename + "\"}");

                //    }
                //    catch (Exception)
                //    {
                //        context.Response.Write("{success:false}");
                //    }
                //    finally
                //    {
                //        fileStream.Close();
                //    }
                //}
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public static void CompressJpegWidth(string strPath, int intWidth, long lngQuality)
        {
            Image img = Image.FromFile(strPath);        // 如果不是图片会出错。
            if (img.Width <= intWidth)
            {
                img.Dispose();
                return;
            }

            int intHeight = img.Height * intWidth / img.Width;

            CompressJpeg(strPath, img, intWidth, intHeight, lngQuality);
        }

        public static void CompressJpegHeight(string strPath, int intHeight, long lngQuality)
        {
            Image img = Image.FromFile(strPath);        // 如果不是图片会出错。
            if (img.Height <= intHeight)
            {
                img.Dispose();
                return;
            }

            int intWidth = img.Width * intHeight / img.Height;

            CompressJpeg(strPath, img, intWidth, intHeight, lngQuality);
        }

        public static void CompressJpeg(string strPath, Image img, int intWidth, int intHeight, long lngQuality)
        {
            
            //var intHeight = img.Height * intWidth / img.Width;
            // 创建位图及相关联的图形处理工具，在位图上画缩略图
            var thm = new Bitmap(intWidth, intHeight);
            var grp = Graphics.FromImage(thm);
            grp.DrawImage(img, 0, 0, intWidth, intHeight);
            // 释放占用的图片文件
            img.Dispose();
            grp.Dispose();
            // 设置图片质量
            var ep = new EncoderParameters(1);
            ep.Param[0] = new EncoderParameter(Encoder.Quality, lngQuality);
            // 保存缩略图
            thm.Save(strPath);        // 如果不设置图片质量，可直接保存
            //thm.Save(strPath, ImageCodecInfo.GetImageEncoders().FirstOrDefault(i => i.MimeType == "image/jpeg"), ep);
            thm.Dispose();
        }
    }
}
